package study_thread;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 *
 * @author: 李德才
 * @description:
 * @create: 2020-12-12 20:09
 **/
public class Test_ReadWriteLock {


    /**
     * 解决线程安全问题使用ReentrantLock就可以了，但是ReentrantLock是独占锁，某一时刻只有一个线程可以获取该锁，
     * 而实际中会有写少读多的场景，显然ReentrantLock满足不了这个需求，
     * 所以ReentrantReadWriteLock应运而生。
     * ReentrantReadWriteLock采用读写分离的策略，允许多个线程可以同时获取读锁
     */

    /**
     * 当一个新线程，首先会将其加入同步队列，其次会调用tryAcquire尝试去执行这个线程。
     * 对于公平锁来说，writerShouldBlock会判断队列是否含还有排队的线程，如果有，返回ture. 不执行新加的线程。
     * 对于非公平锁来说，writerShouldBlock直接返回false,直接执行compareAndSetState------CAS操作
     * 在CAS操作中,其回去请求对象锁，如果对象锁被别的线程占据，则自旋。所以不是按队列顺序去执行线程。
     */

    private static int value;
//    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();

    public static void read(Lock lock) {
        try {
            lock.lock();
            Thread.sleep(1000);
            System.out.println("read over!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void write(Lock lock, int v) {
        try {
            lock.lock();
            Thread.sleep(1000);
            value = v;
            System.out.println("write over!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Runnable readR = () -> read(readLock);
        Runnable writeR = () -> write(writeLock, new Random().nextInt());
        for (int i = 0; i < 18; i++) new Thread(readR).start();
        for (int i = 0; i < 2; i++) new Thread(writeR).start();
    }
}
